# -*- coding: utf-8 -*-
import thread
import time
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler


class Serveur(object):
    def __init__(self):                          #10.57.70.69,11501
        self.server= SimpleXMLRPCServer(("localhost", 8000),allow_none=True,\
                                            requestHandler=SimpleXMLRPCRequestHandler)
        self.server.register_introspection_functions()
        self.BaseDonnees = SimulateurBD()
        self.EnregistrerFonction(self.BaseDonnees)
        self.Demarrer()
        
    def EnregistrerFonction(self,Classe):
        self.server.register_instance(Classe)
    
    def Demarrer(self):
        print 'OK, serveur demarre a '+time.ctime(time.time())
        self.server.serve_forever()
        
    


class SimulateurBD:
    def __init__(self):
        self.Table = {'S_EMP':
                       [['ID',100],['LAST_NAME',100], ['FIRST_NAME',100], ['AGE',100], ['SALARY',100]],
                       'PERP_CONTRAINTES':
                       [["OPERANDE_GAUCHE",100], ["CONDITION",100], ["COMPARAISON",100],
                        ["OPERANDE_DROITE",100], ["ATTRIBUT_GAUCHE",100],["ATTRIBUT_GAUCHE",100],
                        ["MESSAGE_ERREUR",100], ["MESSAGE_GUIDE",100], ["ID_CONTRAINTES",100],
                        ["COMPARAISON",100]]}
        self.S_Emp = []
        self.Perp_Contraintes = []
        self.Select = {'S_EMP': self.S_Emp,
                     'PERP_CONTRAINTES':self.Perp_Contraintes}
        
        self.Perp_Contraintes.append({"OPERANDE_GAUCHE":'S_EMP', 
                                      "CONDITION":'IF',
                                      "COMPARAISON":'>',
                                      "OPERANDE_DROITE":'18',
                                      "ATTRIBUT_DROITE":None, 
                                      "ATTRIBUT_GAUCHE":'AGE',
                                      "MESSAGE_ERREUR":'L''age minimum requis est 18 ans.', 
                                      "MESSAGE_GUIDE":'La personne doit être majeure, i.e. avoir plus de 18 ans.', 
                                      "ID_CONTRAINTES":'1'
                                      })
        self.Perp_Contraintes.append({"OPERANDE_GAUCHE":'S_EMP',
                                      "CONDITION":'IF', 
                                      "COMPARAISON":'<',
                                      "OPERANDE_DROITE":'10000',
                                      "ATTRIBUT_DROITE":None,
                                      "ATTRIBUT_GAUCHE":'SALARY',
                                      "MESSAGE_ERREUR":'Le salaire doit etre inferieur a 10000', 
                                      "MESSAGE_GUIDE":'La personne doit avoir un salaire inferieur a 10000', 
                                      "ID_CONTRAINTES":'2'
                                      })
        self.Perp_Contraintes.append({"OPERANDE_GAUCHE":'S_EMP', 
                                      "CONDITION":'IF', 
                                      "COMPARAISON":'>',
                                      "OPERANDE_DROITE":'18',
                                      "ATTRIBUT_DROITE":None, 
                                      "ATTRIBUT_GAUCHE":'AGE',
                                      "MESSAGE_ERREUR":'L''age minimum requis est 18 ans.', 
                                      "MESSAGE_GUIDE":'La personne doit être majeure, i.e. avoir plus de 18 ans.', 
                                      "ID_CONTRAINTES":'3'
                                      })
        
    def Authentification(self,nom,pwd):
        return[1,"Athentification r�sussite"]
        
        
        
    def RecevoirVue(self,NomVue):       
        f=open('Temp/'+NomVue+'.py','r')         
        p=f.readlines()         
        f.close()         
        return p         
        pass
     
    def ObtenirListeChamps(self,table):
        return [1,self.Table[table]]

    def ObtenirListeTables(self, s = None, sa = None):
        Reponse = []
        for key in self.Table.keys():
            Reponse.append([key])
        return [1,Reponse]
    
    def InsererEnregistrement(self, table, donnees):
        print donnees
        Champs = self.ObtenirListeChamps(table)[1]
        print "keys", Champs
        for Champ in Champs:
            if not donnees.has_key(Champ[0]):
                donnees[Champ[0]] = ""
        print donnees
        self.Select[table].append(donnees)
        return [0,"succes"]
       # prin table, self.Select[table]
    
    def MettreAJour(self, table, donnees, where):
        print donnees
        for index in range(len(self.Select[table])):
            valide = 1
            for clause in where:
                print "test" , self.Select[table][index]
                print clause
                if self.Select[table][index][clause['valeur_gauche']] <> clause['valeur_droite']:
                    valide = 0
            if valide == 1:
                print "avant", self.Select[table]
                self.Select[table][index] = donnees  
                print "apres", self.Select[table]
    
    def EffacerEnregistrement(self, table, where=None):
        enregistrements = []
#        print self.Select[table]
        for index in range(len(self.Select[table])):
           #print self.Select[table][index]
           valide = 1
           if where <> None:
               for clause in where:
#                    print self.Select[table][index]
#                    print clause['valeur_gauche']
#                    print self.Select[table][index][clause['valeur_gauche']], clause['valeur_droite']
                    if self.Select[table][index][clause['valeur_gauche']] <> clause['valeur_droite']:
                       valide = 0
               if valide == 1:
                   del self.Select[table][index]
                   return
#        print self.Select[table]
                   
    def ObtenirEnregistrement(self, table, colonnes=None, where=None):
        enregistrements = []
        for oneEnregistrement in self.Select[table]:
           valide = 1
           if where <> None:
               for clause in where:
                    if oneEnregistrement[clause['valeur_gauche']] <> clause['valeur_droite']:
                       valide = 0
           if valide == 1:
                enregistrement = {}
                for colonne in colonnes:
                    enregistrement[colonne] = oneEnregistrement[colonne]
                enregistrements.append(enregistrement)
        return [1,enregistrements]
   
    def ObtenirContraintes(self, table):
       NomsChamps = []
       for Champ in self.ObtenirListeChamps('PERP_CONTRAINTES')[1]:
           NomsChamps.append(Champ[0])
       where = {'valeur_gauche':'OPERANDE_GAUCHE', 'valeur_droite':table}
       Reponse = self.ObtenirEnregistrement('PERP_CONTRAINTES', NomsChamps, [where])
       return [1,Reponse[1]]  
#enregistrement.update(colonne,(self.Select[table][colonne]))    
serveur=Serveur()
sim = SimulateurBD()
#where = {'valeur_gauche':'ID_CONTRAINTES', 'valeur_droite':'2'}
#print sim.ObtenirEnregistrement('PERP_CONTRAINTES',ListeContraintes, [where])
Contrainte = sim.ObtenirContraintes('S_EMP')[1][0]
##print Contrainte
#where = {'valeur_gauche':'ID_CONTRAINTES', 'valeur_droite':Contrainte['ID_CONTRAINTES']}
#sim.EffacerEnregistrement('PERP_CONTRAINTES', [where])
where = {'valeur_gauche':'ID_CONTRAINTES', 'valeur_droite':Contrainte['ID_CONTRAINTES']}
#where = " ID_CONTRAINTES = " + Contrainte['ID_CONTRAINTES']
sim.MettreAJour('PERP_CONTRAINTES', Contrainte, [where])
#Contrainte = {}
sim.InsererEnregistrement('PERP_CONTRAINTES', Contrainte)